package com.iotmonitor.iot.core;


import com.iotmonitor.iot.domain.TbGps;
import com.iotmonitor.iot.service.ITbGpsService;
import com.iotmonitor.iot.service.ITbQuotaService;
import com.iotmonitor.iot.emq.EmqClient;
import com.iotmonitor.iot.service.TbReportService;
import org.apache.logging.log4j.util.Strings;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 监控类，启动后自动订阅主题
 */
@Component

public class Monitor {

    private static final Logger log = LoggerFactory.getLogger(Monitor.class);

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private ITbQuotaService quotaService;

    @Autowired
    private ITbGpsService gpsService;


    @PostConstruct
    public void init() {
        System.out.println("初始化方法，订阅主题");
        emqClient.connect();
        // 指标订阅
        quotaService.getAllSubject().forEach(s -> {
            // 共享订阅模式 共享队列来接收($queue/)
            try {
                emqClient.subscribe("$queue/" + s);
            } catch (MqttException e) {
                log.error("订阅主题出错：", e);
            }
        });

        // gps订阅, 读取gps配置
        TbGps tbGps = gpsService.getGps();
        // 共享订阅模式
        try {
            // 如果主题不为空
            if (Strings.isNotEmpty(tbGps.getSubject())) {
                emqClient.subscribe("$queue/" + tbGps.getSubject());
            }
        } catch (MqttException e) {
            log.error("订阅主题出错：", e);
        }

    }

}
